/**
 * 
 */
package br.pucpr.server.jogo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;

import br.pucpr.view.TelaPrincipal;

/**
 * @author 2ony
 *
 */
public class ServerMaestro extends Thread {
	
	private TelaPrincipal tela;
	private int porta;
	private ServerSocket serverSocket;
	
	public ServerMaestro(TelaPrincipal tela, int porta) {
		this.tela = tela;
		this.porta = porta;
	}
	
	@Override
	public void run() {
		try {
			serverSocket = new ServerSocket(porta);
		} catch (IOException e) {
			System.out.println("Nao consegui ouvir a porta: " + porta + ", "
					+ e);
			System.exit(1);
		}

		esperarSerChamado();
	}

	@SuppressWarnings("static-access")
	private void esperarSerChamado() {

		while(true){
			Socket cliente = null;
			try {
				cliente = serverSocket.accept();
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			BufferedReader is = null;
			try {
				is = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
			} catch (IOException e1) {
				e1.printStackTrace();
			}

			if (is != null) {
				try {
					String fromServer;

					while ((fromServer = is.readLine()) != null) 
					{
						if (fromServer.equals("ACEITOU")){
							new ThreadOnline(tela).start();
							tela.iniciarTelaJogo(true, "");
							break;
						} else {
							JOptionPane.showMessageDialog(null, "O Jogador recusou o convite", "S E N H A  -  P L A Y", JOptionPane.INFORMATION_MESSAGE);
							break;
						}
					}

				} 
				catch (IOException e) 
				{
					System.err.println("Programa Abortado:  " + e);
				}
			}
		}
	}

}
